package com.sc.es.task;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class ESMonitor {

    private final static String HEALTH_CHECK_API="http://localhost:9200/_cluster/health";

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private JavaMailSender mailSender;


    private static  final  String GREED="green";
    private static  final  String YELLOW="yellow";
    private static  final  String RED="red";


    /**
     * 十秒一次
     */
    @Scheduled(fixedDelay = 10000)
    public void healthCheck()  {
        HttpClient httpClients = HttpClients.createDefault();
        HttpGet get = new HttpGet(HEALTH_CHECK_API);
        try {
            HttpResponse response = httpClients.execute(get);
            if(response.getStatusLine().getStatusCode()!= HttpServletResponse.SC_OK){
                System.out.println("can not access es normally");
            }else{
                String body = EntityUtils.toString(response.getEntity(), "utf-8");
                JsonNode result = objectMapper.readTree(body);
                String status = result.get("status").asText();
                switch (status){
                    case GREED:
                        break;
                    case YELLOW:
                        System.out.println("ES run YELLOW");
                        break;
                    case RED:
                        System.out.println("ES run Red ,must CHECK");
                        sendAlertMessage("ES status == Red,请及时排查问题");
                        break;
                        default:
                            System.out.println("unknown status");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendAlertMessage(String message){
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom("");
        mailMessage.setTo("");
        mailMessage.setSubject("ES监控警告");
        mailMessage.setText(message);
        mailSender.send(mailMessage);
    }
}
